package com.czxy.controller;

import com.czxy.auth.entity.UserInfo;
import com.czxy.auth.util.JwtUtils;
import com.czxy.config.JwtProperties;
import com.czxy.pojo.User;
import com.czxy.pojo.group.BaseResult;
import com.czxy.pojo.group.LoginResult;
import com.czxy.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Liuyunqin 17674029449@163.com
 * @date 2018/12/17 17:27
 */
@RestController
@RequestMapping
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @param user
     * @return
     */
    @PostMapping("login")
    public ResponseEntity<Object> login(@RequestBody User user) {
        //1. 调用Service，查找用户信息
        User userByMobile = this.authService.findUserByMobile(user);
        //2. 如果找不到用户信息，直接报错
        //2. 如果熔断，直接返回失败
        if (userByMobile == null || userByMobile.getId() == -100) {
            BaseResult baseResult = new BaseResult(1, "未找到用户信息");
            return ResponseEntity.ok(baseResult);
        }
        //3. 如果找到了用户信息，生成jwt
        //第一个参数 userInfo
        //第二个参数 私钥
        //第三个参数 存活时间
        UserInfo userInfo = new UserInfo(userByMobile.getId(), userByMobile.getName());

        String token = null;
        try {
            //生成token**
            token = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), 30);
        } catch (Exception e) {
            e.printStackTrace();
            BaseResult baseResult = new BaseResult(1, "服务器异常");
            ResponseEntity.ok(baseResult);
        }

        //4. 根据接口拼接返回结果，返回数据
        LoginResult loginResult = new LoginResult(0, "登录成功！", token, userByMobile.getName());
        return ResponseEntity.ok(loginResult);
    }

}
